package com.copote.pdfutils;

import com.copote.pdfutils.common.PDFFonts;
import com.copote.pdfutils.common.PageHeader;
import com.copote.pdfutils.common.PageMarker;
import com.copote.pdfutils.common.WaterMarker;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;


/**
 * 将多张图片合并转为PDF；需要用到iTextpdf包，
 */
@Slf4j
public class CompositePDFofMultiplePictures {
    // TODO:设置图片为5*5张照片
    // 页边距
    static float Margin = 36;
    //图片高
    static float Hheigth = (PageSize.A4.getHeight() - Margin * 2) / 5;
    //图片宽
    static float Wwidth = (PageSize.A4.getWidth() - Margin * 2) / 5;
    static int FontSize = 12;

    /**
     * 把批量照片生成PDF文档.
     * @param FileList 文件图片文件名称(带路径)数组
     * @param Title 标题文字
     * @param WaterStr 水印文字
     * @param PdfFile 输出PDF文件名
     */
    public static void PictoPdf(String[][] FileList, String Title, String WaterStr, String PdfFile) {
        try {
            //总页数
            int pagetotal = 0;
            String RootPath = ResourceUtils.getURL("classpath:").getPath();
            String BLACKPic = RootPath + "/black.png";//空白图片
            String headerPic = RootPath + "/water.png";//标题图片

            //获取中文字体
            PdfFont font = PDFFonts.getPDFFont();

            //TODO:限制PDF修改，只能打印
            final String OWNER_PASSWORD = "Security";
            WriterProperties wp = new WriterProperties();
            wp.setStandardEncryption(null, OWNER_PASSWORD.getBytes(), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
            PdfWriter writer = new PdfWriter(PdfFile, wp);

            PdfDocument pdf = new PdfDocument(writer);//(new PdfWriter(PdfFile, new WriterProperties().addUAXmpMetadata()));
            pdf.setDefaultPageSize(PageSize.A4);
            // 水印
            pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarker(WaterStr, font));
            // 页眉
            pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PageHeader(headerPic, Title, font));
            // 页码
            pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PageMarker(pagetotal,font));

            //Setting some required parameters
            pdf.setTagged();
            pdf.getCatalog().setLang(new PdfString("zh_CN"));
            pdf.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
            pdf.getCatalog().setPageLayout(PdfName.Pages);
            PdfDocumentInfo info = pdf.getDocumentInfo();
            //String Title = "ETC订单上传车辆图片展示";
            info.setTitle(Title);//标题
            info.setSubject(Title);//主题
            info.setKeywords(Title);//关键字
            info.setAuthor(WaterStr);//作者
            info.setCreator("Test系统");

            Document doc = new Document(pdf, PageSize.A4);
            doc.setFontSize(FontSize);
            doc.setMargins(Margin + 10, Margin, Margin, Margin);

            for (int i = 0; i < FileList.length; i++) {
                //TODO:一次处理一个订单的图片的7张图片
                //TODO：检测图片是否存在，不存在则置空图片
                String order = "";
                String[] FileName = {BLACKPic, BLACKPic, BLACKPic, BLACKPic, BLACKPic, BLACKPic, BLACKPic};
                for (int j = 0; j < FileList[i].length; j++) {
                    log.debug("List[" + j + "]:" + FileList[i][j]);
                    File file1 = new File(FileList[i][j]);
                    if (file1.exists()
                            && (file1.getName().endsWith(".jpg") || file1.getName().endsWith(".png")
                            || file1.getName().endsWith(".gif") || file1.getName().endsWith(".jpeg")
                            || file1.getName().endsWith(".tif"))) {
                        order = file1.getName().substring(0, file1.getName().lastIndexOf("_"));
                        if (file1.getName().contains("_3")) {//驾驶证正页
                            FileName[2] = FileList[i][j];
                        } else if (file1.getName().contains("_4")) {//驾驶证附页
                            FileName[3] = FileList[i][j];
                        } else if (file1.getName().contains("_5")) {//车头照
                            FileName[4] = FileList[i][j];
                        } else if (file1.getName().contains("_6")) {//车内照，含OBU的照片
                            FileName[5] = FileList[i][j];
                        } else if (file1.getName().contains("_7")) {//车外照，保护OBU的图片
                            FileName[6] = FileList[i][j];
                        } else {
                            //0:车主身份证正面,1:车主身份证背面，不需要输出
                            continue;
                        }
                    }
                }
                //TODO：读入一个订单的图片
                Paragraph p = new Paragraph().setFont(font);
                Paragraph p1 = new Paragraph().setFont(font);
                Image img = null;
                for (int j = 2; j < 7; j++) {
                    String name = FileName[j].substring(FileName[j].lastIndexOf("/") + 1);
                    img = new Image(ImageDataFactory.create(FileName[j]));
                    //TODO:按照比例压缩
                    float width = img.getImageWidth();
                    float heigth = img.getImageHeight();
                    float percent = Math.min(Hheigth / heigth, Wwidth / width);
                    log.debug("{}：【({}:{})-({}:{})】-压缩比：{}", name, Hheigth, Wwidth, heigth, width, percent);
                    img.scaleToFit(width * percent, heigth * percent);
                    //PDF/UA: Set alt text
                    img.getAccessibilityProperties().setAlternateDescription(name);
                    p.add(img);
                }
                p1.add("订单号:【" + order + "】");
                log.info("第【{}】批次-{}-照片处理完成。",i,order);
                log.debug("PdfFile:{}",PdfFile);
                doc.add(p1);
                doc.add(p);
            }
            doc.close();
            pdf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
